package com.itheima.stock.handler;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.itheima.stock.utils.WebUtils;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import org.checkerframework.checker.units.qual.C;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * security认证失败处理器
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authException) throws IOException, ServletException {
        //BadCredentialsException 密码错误
        if (authException.getClass().isAssignableFrom(BadCredentialsException.class)){
            R result = R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
            String json = JSON.toJSONString(result);
            WebUtils.renderString(httpServletResponse, json);
        }

    }
}
